package com.jiedeng.controller;

import com.jiedeng.dao.*;
import com.jiedeng.model.*;
import com.jiedeng.util.QiniuUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 覃远龙
 * @ClassName: BusinessController
 * @Description:
 * @date 2017/8/4 10:07
 */
@RestController
@RequestMapping("/biz")
public class BusinessController {

    @Autowired
    IProjectRepository projectRepository;

    @Autowired
    IProjectCorpRepository projectCorpRepository;

    @Autowired
    IProjectPersonRepository projectPersonRepository;

    @Autowired
    IOrderRepository orderRepository;

    @Autowired
    ITaskRepository taskRepository;

    @Autowired
    IEventRepository eventRepository;

    @Autowired
    ICheckRepository checkRepository;

    @Autowired
    ICheckCountRepository checkCountRepository;
    @Autowired
    IFileRecordRepository fileRecordRepository;
    @Autowired
    ISysMessageRepository sysMessageRepository;
    @Autowired
    ISysMsgHandleRepository sysMsgHandleRepository;

    //----------------- project table -------------------//
    @RequestMapping(value = "/project/all", method = RequestMethod.GET)
    public List<Project> findAllProject() {
        return projectRepository.findAll();
    }

    @RequestMapping(value = "/project/findByStatus", method = RequestMethod.GET)
    public List<Project> findByStatus(int status) {
        return projectRepository.findByStatus(status);
    }

    @RequestMapping(value = "/project/{id}", method = RequestMethod.GET)
    public Project findProject(long id) {
        return projectRepository.getOne(id);
    }

    @RequestMapping(value = "/project/findProjectById", method = RequestMethod.GET)
    public Project findProjectById(long id) {
        return projectRepository.findById(id).get();
    }

    @RequestMapping(value = "/project/save", method = RequestMethod.POST)
    public Project saveProject(@RequestBody Project project) {
        return projectRepository.save(project);
    }

    @RequestMapping(value = "/project/delete", method = RequestMethod.POST)
    public void deleteProject(long id) {
        projectRepository.deleteById(id);
    }

    //----------------- project_corp table -------------------//
    @RequestMapping(value = "/project_corp/all", method = RequestMethod.GET)
    public List<ProjectCorp> findAllProjectCorps() {
        return projectCorpRepository.findAll();
    }

    @RequestMapping(value = "/project_corp/{id}", method = RequestMethod.GET)
    public ProjectCorp findProjectCorp(long id) {
        return projectCorpRepository.getOne(id);
    }

    @RequestMapping(value = "/project_corp/save", method = RequestMethod.POST)
    public ProjectCorp saveProject(@RequestBody ProjectCorp projectCorp) {
        return projectCorpRepository.save(projectCorp);
    }

    @RequestMapping(value = "/project_corp/delete", method = RequestMethod.POST)
    public void deleteProjectCorp(long id) {
        projectCorpRepository.deleteById(id);
    }

    //----------------- projectPerson table -------------------//
    @RequestMapping(value = "/project_person/all", method = RequestMethod.GET)
    public List<ProjectPerson> findAllProjectPerson() {
        return projectPersonRepository.findAll();
    }

    @RequestMapping(value = "/project_person/{id}", method = RequestMethod.GET)
    public ProjectPerson findProjectPerson(long id) {
        return projectPersonRepository.getOne(id);
    }

    @RequestMapping(value = "/project_person/save", method = RequestMethod.POST)
    public ProjectPerson saveProjectPerson(@RequestBody ProjectPerson projectPerson) {
        return projectPersonRepository.save(projectPerson);
    }

    @RequestMapping(value = "/project_person/delete", method = RequestMethod.POST)
    public void deleteProjectPerson(long id) {
        projectPersonRepository.deleteById(id);
    }

    //----------------- order table -------------------//
    @RequestMapping(value = "/order/all", method = RequestMethod.GET)
    public List<Order> findAllOrder() {
        return orderRepository.findAll();
    }

    @RequestMapping(value = "/order/{id}", method = RequestMethod.GET)
    public Order findOrder(long id) {
        return orderRepository.getOne(id);
    }

    @RequestMapping(value = "/order/save", method = RequestMethod.POST)
    public Order saveOrder(@RequestBody Order order) {
        return orderRepository.save(order);
    }

    @RequestMapping(value = "/order/delete", method = RequestMethod.POST)
    public void deleteOrder(long id) {
        orderRepository.deleteById(id);
    }


    //----------------- task table -------------------//
    @RequestMapping(value = "/task/all", method = RequestMethod.GET)
    public List<Task> findAllTask() {
        return taskRepository.findAll();
    }

    @RequestMapping(value = "/task/{id}", method = RequestMethod.GET)
    public Task findTask(String id) {
        return taskRepository.getOne(id);
    }

    @RequestMapping(value = "/task/findTaskById", method = RequestMethod.GET)
    public Task findTaskById(String id) {
        return taskRepository.findById(id).get();
    }

    @RequestMapping(value = "/task/save", method = RequestMethod.POST)
    public Rst saveTask(@RequestBody Task task) {
        Rst rst = new Rst();
        try {
            taskRepository.save(task);
            rst.setResultCode(0);
            rst.setMsg("OK");
        } catch (Exception e) {
            rst.setResultCode(1);
            rst.setMsg("Mysql Error");
        }
        return rst;
    }

    @RequestMapping(value = "/task/delete", method = RequestMethod.POST)
    public void deleteTask(String id) {
        try {
            Task task=taskRepository.getOne(id);
            taskRepository.delete(task);
            List<SysMessage> sysMessageList = sysMessageRepository.findByParamsLike("%" + id + "%");
            sysMessageList.forEach(sysMessage -> {
                sysMessageRepository.delete(sysMessage);
                sysMsgHandleRepository.deleteByMsgId(sysMessage.getId());
            });
        }catch (Exception e){
          e.printStackTrace();
        }
    }

    @RequestMapping(value = "/filterTask", method = RequestMethod.GET)
    public List<Task> filterTask(final long taskPersonId, String excutePersonId, final long closePersonId, final long pubPersonId, final long verifyPersonId, final long projectId) {
        Specification<Task> sp = new Specification<Task>() {
            @Override
            public Predicate toPredicate(Root<Task> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                if (taskPersonId > 0) {
                    predicates.add(criteriaBuilder.equal(root.get("taskPersonId"), taskPersonId));
                }
                if (closePersonId > 0) {
                    predicates.add(criteriaBuilder.equal(root.get("closePersonId"), closePersonId));
                }
                if (pubPersonId > 0) {
                    predicates.add(criteriaBuilder.equal(root.get("pubPersonId"), pubPersonId));
                }
                if (verifyPersonId > 0) {
                    predicates.add(criteriaBuilder.equal(root.get("verifyPersonId"), verifyPersonId));
                }
                //predicates.add(criteriaBuilder.equal(root.get("isDelete"), isDelete));
                if (projectId > 0) {
                    predicates.add(criteriaBuilder.equal(root.get("projectId"), projectId));
                }

                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };

        List<Task> tasks = taskRepository.findAll(sp);

        List<Task> taskFilter = new ArrayList<Task>();
        for (Task t : tasks) {
            if (t.getExcutePersonId().contains(excutePersonId)) {
                taskFilter.add(t);
            }
        }
        return taskFilter;

    }

    @RequestMapping(value = "/filterTask2", method = RequestMethod.GET)
    public List<Task> filterTask2(final long taskPersonId, String excutePersonId, final long closePersonId, final long pubPersonId, final long verifyPersonId, final long projectId, final Boolean isClose, final Boolean isCloseDo) {
        Specification<Task> sp = new Specification<Task>() {
            @Override
            public Predicate toPredicate(Root<Task> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                if (taskPersonId > 0) {
                    predicates.add(criteriaBuilder.equal(root.get("taskPersonId"), taskPersonId));
                }
                if (closePersonId > 0) {
                    predicates.add(criteriaBuilder.equal(root.get("closePersonId"), closePersonId));
                }
                if (pubPersonId > 0) {
                    predicates.add(criteriaBuilder.equal(root.get("pubPersonId"), pubPersonId));
                }
                if (verifyPersonId > 0) {
                    predicates.add(criteriaBuilder.equal(root.get("verifyPersonId"), verifyPersonId));
                }
                //predicates.add(criteriaBuilder.equal(root.get("isDelete"), isDelete));
                if (projectId > 0) {
                    predicates.add(criteriaBuilder.equal(root.get("projectId"), projectId));
                }
                if (isClose != null) {
                    predicates.add(criteriaBuilder.equal(root.get("isClose"), isClose));
                }
                if (isCloseDo != null) {
                    predicates.add(criteriaBuilder.equal(root.get("isCloseDo"), isCloseDo));
                }

                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };

        List<Task> tasks = taskRepository.findAll(sp);

        List<Task> taskFilter = new ArrayList<Task>();
        for (Task t : tasks) {
            if (t.getExcutePersonId().contains(excutePersonId)) {
                taskFilter.add(t);
            }
        }
        return taskFilter;

    }

    //----------------- event table -------------------//
    @RequestMapping(value = "/event/all", method = RequestMethod.GET)
    public List<Event> findAllEvent() {
        return eventRepository.findAll();
    }

    @RequestMapping(value = "/event/{id}", method = RequestMethod.GET)
    public Event findEvent(String id) {
        return eventRepository.getOne(id);
    }

    @RequestMapping(value = "/event/save", method = RequestMethod.POST)
    public Event saveTask(@RequestBody Event event) {
        return eventRepository.save(event);
    }

    @RequestMapping(value = "/event/delete", method = RequestMethod.POST)
    public void deleteEvent(String id) {
        eventRepository.deleteById(id);
    }

    //----------------- check table -------------------//
    @RequestMapping(value = "/check/all", method = RequestMethod.GET)
    public List<Check> findAllCheck() {
        return checkRepository.findAll();
    }

    @RequestMapping(value = "/check/{id}", method = RequestMethod.GET)
    public Check findCheck(String id) {
        return checkRepository.getOne(id);
    }

    @RequestMapping(value = "/check/save", method = RequestMethod.POST)
    public Check saveCheck(@RequestBody Check check) {
        return checkRepository.save(check);
    }

    @RequestMapping(value = "/check/delete", method = RequestMethod.POST)
    public void deleteCheck(String id) {
        checkRepository.deleteById(id);
        //FileRecord
        List<FileRecord> fileRecordList = fileRecordRepository.findByCheckId(id);
        for (FileRecord fileRecord : fileRecordList) {
            QiniuUtil qiniuUtil = new QiniuUtil();
            qiniuUtil.delete(fileRecord.getOldPhotoPath());
            fileRecordRepository.delete(fileRecord);
        }
        List<CheckCount> checkCountList = checkCountRepository.findByCheckId(id);
        for (CheckCount checkCount : checkCountList) {
            checkCountRepository.delete(checkCount);
        }
    }

    //----------------- checkCount table -------------------//
    @RequestMapping(value = "/check_count/all", method = RequestMethod.GET)
    public List<CheckCount> findAllCheckCount() {
        return checkCountRepository.findAll();
    }

    @RequestMapping(value = "/check_count/{id}", method = RequestMethod.GET)
    public CheckCount findCheckCount(String id) {
        return checkCountRepository.getOne(id);
    }

    @RequestMapping(value = "/check_count/save", method = RequestMethod.POST)
    public CheckCount saveCheckCount(@RequestBody CheckCount check) {
        return checkCountRepository.save(check);
    }

    @RequestMapping(value = "/check_count/delete", method = RequestMethod.POST)
    public void deleteCheckCount(String id) {
        checkCountRepository.deleteById(id);
    }
}

